# 10.3.1 处理ZeroDivisionError 异常
# 10.3.2 使用try-except 代码块
# try:
#     print(5 / 0)
# except ZeroDivisionError:
#     print("被除数不能为零")

# 10.3.3 使用异常避免崩溃
# 10.3.4 else 代码块
# print("请输入一个数字，进行相除。.")
# print("输入'q' 退出.")
# while True:
#     first_number = input("\n第一个数字: ")
#     if first_number == 'q':
#         break
#     second_number = input("第二个数字: ")
#     try:
#         answer = int(first_number) / int(second_number)
#     except ZeroDivisionError:
#         print("被除数不能为零")
#     else:
#         print(answer)

# 10.3.5 处理FileNotFoundError 异常
# file_name="money.txt"
# try:
#     with open(file_name) as f_obj:
#         contents=f_obj.read()
# except FileNotFoundError:
#     msg="file_name"+"文件不存在！"
#     print(msg)

# 10.3.6 分析文本
# 方法split() 以空格为分隔符将字符串分拆成多个部分
title = "Alice in Wonderland"
print(title.split())


#
# filename = 'alice.txt'
# try:
#     with open(filename) as f_obj:
#         contents = f_obj.read()
# except FileNotFoundError:
#     msg = "对不起，文件" + filename + " 不存在."
#     print(msg)
# else:
#     # 计算文件大致包含多少个单词
#     words = contents.split()
#     num_words = len(words)
#     print("The file " + filename + " has about " + str(num_words) + " words.")

# 10.3.7 使用多个文件
def count_words(filename):
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "对不起，文件" + filename + " 不存在."
        print(msg)
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")


filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)

# 10.3.8 失败时一声不吭
try:
    print("hello")
except FileNotFoundError:
    # 忽略
    pass
else:
    print("其他")
